import React, {useEffect, useState} from 'react';
import { Form, Button,TreeSelect,Upload,Input, Modal,Row,message, Col,InputNumber,Select} from 'antd';
import { connect } from 'umi';
import {UploadOutlined,PlusOutlined} from '@ant-design/icons';
import {getUploadUrl} from '@/utils/upload'
import DetailedTable from './DetailedTable';
import AllocationTable from "./AllocationTable";
import {getPerformanceRatioById} from '../service';
import {resultSum} from "@/utils/utils";

const FormItem = Form.Item;
const {TextArea} = Input;
const formLayout = {
  labelCol: { span: 7 },
};
const colStyle = {
  xl: 12,
  lg: 12,
  md: 12,
  sm: 12,
  xs: 12,
};

let uploadedFiles = [];

const DetailedAllocationForm = (props) => {
  const { onSubmit, onCancel, loading,visible,currentUser} = props;
  const [form] = Form.useForm();
  const [fileUploadUrls,setFileUploadUrls] = useState([]);
  const [fileName, setFileName] = useState(null);
  const [scaleInfo,setScaleInfo] = useState({});
  const [enterNum,setEnterNum] = useState(0);
  const [tempRecord,setTempRecord] = useState({});


  const fileList = {
    name: 'file',
    multiple: true,
    action: getUploadUrl(),
    data: {name: fileName},
    defaultFileList: uploadedFiles,
    beforeUpload(file) {
      setFileName(file.name)
    },
    onChange(res) {
      const {status} = res.file;
      if (status === 'done') {
        if (res.file.response.error) {
          message.success(`${res.file.response.error}`);
        } else {
          setFileUploadUrls([...fileUploadUrls,res.file.response ]);
          message.success(`${res.file.name} 文件上传成功`);
        }
      } else if (status === 'error') {
        message.error(`${res.file.name} 文件上传失败`);
      }
    },
    onRemove(info) {
      let urls = fileUploadUrls;
      let index = urls.indexOf(info.url);
      if (index > -1){
        urls.splice(index, 1);
        setFileUploadUrls(urls);
      }
    },
  };

  useEffect(() => {
    if(currentUser && visible){
      getPerformanceRatioById(2).then(res => {
        setScaleInfo(res);
      });
    }
  }, [visible]);

  const onFormCancel = () => {
    form.resetFields();
    uploadedFiles = [];
    setFileUploadUrls([]);
    onCancel();
  };

  const handleSubmit = async () => {
    if(resultSum(tempRecord) !== enterNum){
      message.error("分配数量不一致，请核实后再提交！");
      return;
    }
    const fieldsValue = await form.validateFields();
    // form.resetFields();
    // let fileUploadUrlsStr = '';
    // fileUploadUrls.forEach(item => {
    //   if (item){
    //     if (fileUploadUrlsStr === ''){
    //       fileUploadUrlsStr += item;
    //     }else {
    //       fileUploadUrlsStr += ',' + item;
    //     }
    //   }
    // });
    // onSubmit({
    //   ...fieldsValue,
    //   uploadFile:fileUploadUrlsStr,
    // });
    uploadedFiles = [];
    setFileUploadUrls([]);
  };

  const onCompute = (list) => {
    let t = {};
    t.percentageA = list.filter(item => item.performance === 'A').length;
    t.percentageBPlus = list.filter(item => item.performance === 'B+').length;
    t.percentageB = list.filter(item => item.performance === 'B').length;
    t.percentageC = list.filter(item => item.performance === 'C').length;
    t.percentageD = list.filter(item => item.performance === 'D').length;
    setTempRecord(t);
  };



  const renderContent = () => {
    return (
      <>
        <Row gutter={24}>
          <Col {...colStyle}>
            <FormItem name="oprationId" label="单位名称">
              <Input disabled={true}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="oprationName" label="单位绩效">
              <Input disabled={true}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="orgName" label="考核年度" >
              <TreeSelect disabled={true}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="unitName" label="考核周期" >
              <TreeSelect disabled={true}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="jobName" label="单位总人数">
              <Input disabled={true}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="number" label="参加考核人数" rules={[{required: true, message: '参加考核人数不能为空'}]}>
              <InputNumber style={{width: '100%'}} placeholder="请输入考核人数" min={0} onChange={(num) => setEnterNum(num || 0)}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="reason" label="绩效说明">
              <TextArea rows={2}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="uploadFile" label="上传附件" rules={[{required: true, message: '附件不能为空'}]}>
              <Upload {...fileList}>
                <Button>
                  <UploadOutlined/> 点击上传附件
                </Button>
              </Upload>
            </FormItem>
          </Col>
          <Col span={24}>
            <FormItem name="list">
              <AllocationTable scaleInfo={scaleInfo} tempRecord={tempRecord}  enterNum={enterNum}/>
            </FormItem>
          </Col>
          <Col span={24}>
            <FormItem name="list2">
              <DetailedTable onCompute={onCompute}/>
            </FormItem>
          </Col>
        </Row>
      </>
    )
  };

  const renderFooter = () => {
    return (
      <>
        <Button onClick={() => onFormCancel()}>取消</Button>
        <Button type="primary" onClick={() => handleSubmit()} loading={loading}>提交</Button>
      </>
    )
  };

  return (
    <Modal
      width={'70%'}
      destroyOnClose
      centered
      title={`详细分配`}
      visible={visible}
      footer={renderFooter()}
      onOk={handleSubmit}
      onCancel={() => onFormCancel()}
      onClose={() => onFormCancel()}
      okText="确认"
      cancelText="取消"
    >
      <Form
        {...formLayout}
        form={form}
        style={{ paddingTop: '24px' }}
      >
        {renderContent()}
      </Form>
    </Modal>
  )
};

export default connect(({user}) => ({
  currentUser: user.currentUser,
}))(DetailedAllocationForm);
